<template>
	<div v-loading="loading" class="cr-body-content">
		<flexbox class="content-header" justify="flex-start" align="flex-start">
			<CRMRelativeSearch
				ref="search"
				:crm-type="crmType"
				@field-geted="setTableHeight"
				class="search-container"
			/>
			<el-button class="header-button" type="primary" @click="handleSearch"
				>查询</el-button
			>
			<a
				download
				target="_blank"
				href="/api/CrmReceivables/downSearchTemplate"
				v-if="showDownloadTemplate"
				style="
					text-decoration: underline;
					padding: 0 5px;
					color: #5f88ff;
					line-height: 34px;
				"
				>下载模板</a
			>
			<el-button
				v-if="createable"
				class="header-button"
				type="primary"
				@click="
					!['product', 'program'].includes(crmType)
						? (isCreate = true)
						: $emit('create', crmType)
				"
				>新建</el-button
			>
		</flexbox>
		<div class="content-body" ref="tableWrap">
			<el-table
				ref="relativeTable"
				:class="{ single: radio }"
				:data="list"
				:height="tableHeight"
				class="cr-table"
				stripe
				border
				highlight-current-row
				@selection-change="handleSelectionChange"
				@row-click="handleRowClick"
				@select-all="handleSelectAll"
			>
				<el-table-column
					type="selection"
					:selectable="checkSelectAble"
					align="center"
					width="55"
				/>
				<el-table-column type="index" />
				<el-table-column
					v-for="(item, index) in fieldList"
					:key="index"
					:prop="item.fieldName"
					:label="item.name"
					:width="item.width || 150"
					show-overflow-tooltip
				/>
				<el-table-column />
			</el-table>
		</div>

		<div class="table-footer">
			<el-button :disabled="currentPage <= 1" @click.native="changePage('up')"
				>上一页</el-button
			>
			<el-button
				:disabled="currentPage >= totalPage"
				@click.native="changePage('down')"
				>下一页</el-button
			>
			<el-select
				v-model="currentLimit"
				@change="handleLimitChange"
				style="width: 100px; margin-left: 8px"
			>
				<el-option :value="10" label="每页10条"></el-option>
				<el-option :value="20" label="每页20条"></el-option>
				<el-option :value="50" label="每页50条"></el-option>
				<el-option :value="100" label="每页100条"></el-option>
				<el-option :value="99999" label="显示全部"></el-option>
			</el-select>
			<p style="margin-left: 8px">
				共{{ totalPage }}页 当前第 {{ currentPage }} 页
				<span v-for="foot in footer" :key="foot.name">
					{{ getFootContent(foot) }}
				</span>
			</p>
			<el-button
				type="primary"
				style="margin-left: 8px"
				@click.native="createByNum"
				v-if="crmType == 'contract' && list.length === 0 && !loading"
				>无保单录入</el-button
			>
			<el-button plain style="margin-left: 8px" @click.native="clearSelected"
				>清空已选</el-button
			>
		</div>
		<c-r-m-create-view
			v-if="isCreate"
			:crm-type="crmType"
			@save-success="getList"
			@hiden-view="isCreate = false"
		/>
	</div>
</template>
<script type="text/javascript">
import crmTypeModel from '@/views/customermanagement/model/crmTypeModel'
import {
	crmSceneIndex,
	filedGetTableField,
	crmMainIndex
} from '@/api/customermanagement/common'
// 客户下订单和联系人
import {
	crmCustomerQueryBusiness,
	crmCustomerQueryContract,
	crmCustomerQueryContacts
} from '@/api/customermanagement/customer'

import { getDateFromTimestamp } from '@/utils'
import CRMRelativeSearch from '@/components/createCom/CrmRelativeSearch'

export default {
	name: 'CrmRelativeTable', // 相关模块CRMCell
	inject: {
		createFields: {
			default: ''
		},
		crmRelative: {
			default: ''
		}
	},
	components: {
		CRMRelativeSearch,
		CRMCreateView: () =>
			import('@/views/customermanagement/components/CRMCreateView')
	},
	props: {
		show: {
			type: Boolean,
			default: false
		},
		/** 多选框 只能选一个 */
		radio: {
			type: Boolean,
			default: true
		},
		/** 新建按钮 是否显示 */
		createable: {
			type: Boolean,
			default: false
		},
		/** 没有值就是全部类型 有值就是当个类型 */
		crmType: {
			type: String,
			default: ''
		},
		/** 已选信息 */
		selectedData: {
			type: Object,
			default: () => {
				return {}
			}
		},
		// 禁止操作勾选的行
		disabledRows: {
			type: Array,
			default: () => []
		},
		/**
		 * default 默认  condition 固定条件筛选
		 * relative: 相关 添加
		 */
		action: {
			type: Object,
			default: () => {
				return {
					type: 'default',
					data: {}
				}
			}
		},
		// 表格底部额外信息
		footer: {
			type: Array,
			default: () => []
		},
		// 获取列表的查询条件
		query: Object,
		beforeFetchList: Function
	},
	data() {
		return {
			loading: false, // 加载进度
			searchModel: {}, // 搜索内容
			isCreate: false, // 控制新建
			scenesList: [], // 场景信息
			sceneInfo: null,

			list: [], // 表数据
			fieldList: [], // 表头数据
			currentPage: 1, // 当前页数
			totalPage: 1, // 总页数
			tableHeight: 0,
			currentLimit: 10,
			selectedItem: [] // 当前页勾选的数据，selectedData是所有页面已勾选的数据(包含全部分页)
		}
	},
	computed: {
		// 展示相关效果 去除场景
		isRelationShow() {
			return this.action.type === 'condition'
		},
		showDownloadTemplate() {
			return this.crmType === 'payable'
		}
	},
	watch: {
		crmType: function (newValue, oldValue) {
			if (newValue != oldValue) {
				this.fieldList = []
				this.getFieldList()
			}
		},
		action: function (val) {
			if (this.action != val) {
				this.sceneInfo = null
				this.list = [] // 表数据
				this.fieldList = [] // 表头数据
				this.currentPage = 1 // 当前页数
				this.totalPage = 1 // 总页数
				if (!this.isRelationShow) {
					this.getSceneList()
				} else {
					this.getFieldList()
				}
			}
		},
		show: {
			handler(val) {
				if (val) {
					// 相关列表展示时不需要场景 直接获取展示字段
					if (!this.isRelationShow) {
						this.getSceneList()
					} else {
						this.getFieldList()
					}
				}
			},
			deep: true,
			immediate: true
		},
		// 选择
		selectedData: function (val) {
			this.checkItemsWithSelectedData()
		}
	},
	methods: {
		checkSelectAble(row) {
			const key = this.crmType.replace('personal', '') + 'Id'
			var selected = this.disabledRows.find((_row, index) => {
				return _row[key] == row[key]
			})
			return selected == null
		},
		setTableHeight() {
			this.tableHeight = this.$refs.tableWrap.offsetHeight
		},
		getSceneList() {
			this.loading = true
			crmSceneIndex({
				type: crmTypeModel[this.crmType]
			})
				.then((res) => {
					var defaultScene = res.data.filter(function (item, index) {
						return item.isDefault === 1
					})
					this.scenesList = res.data
					if (defaultScene && defaultScene.length > 0) {
						this.sceneInfo = defaultScene[0]
					}
					if (this.scenesList.length == 0) {
						this.scenesList.push({ sceneId: '', name: '全部' })
						this.sceneInfo = this.scenesList[0]
					}
					this.getFieldList()
				})
				.catch(() => {
					this.loading = false
				})
		},
		/** 获取字段 */
		async getFieldList() {
			try {
				if (this.fieldList.length == 0) {
					await this.getDefaultField()
				}
				// 获取好字段开始请求数据
				await this.getList()
			} catch (e) {
				console.log(e)
			}
		},
		/** 获取列表请求 */
		getDefaultField() {
			this.loading = true
			return filedGetTableField({
				label: crmTypeModel[this.crmType]
			})
				.then((res) => {
					this.loading = false
					this.fieldList = res.data
				})
				.catch((e) => {
					this.loading = false
					return Promise.reject(e)
				})
		},
		/** 获取列表数据 */
		getList() {
			this.loading = true
			let crmIndexRequest = crmMainIndex
			const searchModel = {
				...this.query,
				...this.searchModel
			}
			const params = {
				searchModel,
				tableType: 'relative' // 区别于index表
			}
			// 注入场景
			if (this.sceneInfo) {
				params.sceneId = this.sceneInfo.sceneId
			}
			// 注入关联ID
			if (this.isRelationShow) {
				// this.action.data.moduleType 下的 this.crmType 的列表
				if (this.action.data.moduleType) {
					try {
						crmIndexRequest = {
							customer: {
								business: crmCustomerQueryBusiness,
								businesspersonal: crmCustomerQueryBusiness,
								contacts: crmCustomerQueryContacts,
								contract: crmCustomerQueryContract,
								contractpersonal: crmCustomerQueryContract
							}
						}[this.action.data.moduleType][this.crmType]
					} catch (e) {}

					params[this.action.data.moduleType + 'Id'] =
						this.action.data[this.action.data.moduleType + 'Id']
					if (this.action.data.params) {
						for (const field in this.action.data.params) {
							params[field] = this.action.data.params[field]
						}
					}
				}
				// 2020-10-20 添加
				params.page = this.currentPage
				params.limit = this.currentLimit
				params.type = crmTypeModel[this.crmType]
			} else {
				params.page = this.currentPage
				params.limit = this.currentLimit
				params.type = crmTypeModel[this.crmType]
			}
			if (this.tableUrl) {
				this.tableUrl
					.split('?')[1]
					.split('&')
					.forEach((item) => {
						if (item !== '') {
							// 例：item == type=1
							const key = item.split('=')[0]
							params[key] = item.split('=')[1]
						}
					})
				crmIndexRequest = (data) =>
					axios({
						url: '/api' + this.tableUrl.split('?')[0].split('/api')[1],
						method: 'post',
						data
					})
			}

			return crmIndexRequest(params)
				.then(async (res) => {
					this.list = res.data.list
					/**
					 *  如果已选择的有数据
					 */

					if (this.selectedData[this.crmType]) {
						this.checkItemsWithSelectedData()
					}
					this.totalPage = res.data.totalPage
					this.loading = false
					this.setTableHeight()
				})
				.catch((e) => {
					this.loading = false
					return Promise.reject(e)
				})
		},
		// 标记选择数据
		checkItemsWithSelectedData() {
			const selectedArray = this.selectedData[this.crmType]
			const selectedRows = []
			const key = this.crmType.replace('personal', '') + 'Id'
			this.list.forEach((item, index) => {
				selectedArray.forEach((selectedItem, selectedIndex) => {
					if (item[key] === selectedItem[key]) {
						selectedRows.push(item)
					}
				})
			})

			// debugger
			this.$nextTick(() => {
				this.$refs.relativeTable.clearSelection()
				selectedRows.forEach((row) => {
					this.$refs.relativeTable.toggleRowSelection(row)
				})
			})
		},
		// 分页大小改变
		handleLimitChange() {
			this.getList()
		},
		// 搜索组件事件处理
		handleSearch() {
			this.searchModel = this.$refs.search.getSubmitValue()
			this.currentPage = 1
			if (this.searchModel.entity.file_id) {
				this.currentLimit = 99999
			} else {
				this.currentLimit = 10
			}
			this.getList().then(() => {
				if (this.searchModel.entity.file_id) {
					this.$nextTick(() => {
						this.$refs.relativeTable.clearSelection()

						this.list.forEach(this.$refs.relativeTable.toggleRowSelection)

						this.$nextTick(() => {
							this.crmRelative.confirmClick()
						})
					})
				}
			})
		},
		// 下载模板
		handleDownload() {
			window.open('/api/CrmReceivables/downSearchTemplate', '_blank')
		},
		// 场景选择
		handleTypeDrop(command) {
			this.sceneInfo = command
			this.getList()
		},
		/** 列表操作 */
		// 当某一行被点击时会触发该事件
		handleRowClick(row, column, event) {},
		// 当点击全选时会触发该事件
		handleSelectAll(selection) {
			if (this.radio) return
			// 全选or取消全选
			if (selection.length) {
				this.selectAll = true
			} else {
				this.selectAll = false
			}
		},
		// 当选择项发生变化时会触发该事件
		handleSelectionChange(val) {
			// 如果没有全部选中，把全选设为false
			if (val.length === this.currentLimit) {
				this.selectAll = false
			}
			// debugger
			// 判断单选/多选
			if (this.radio) {
				// this.$refs.relativeTable.clearSelection();
				val.forEach((row, index) => {
					if (index === val.length - 1) return
					this.$refs.relativeTable.toggleRowSelection(row, false)
				})
				if (val.length === 0) {
					this.selectedItem = []
				} else {
					this.selectedItem = val.length === 1 ? val : [val[val.length - 1]]
				}
			} else {
				this.selectedItem = val
			}
			// ------

			let selectedData = this.radio
				? []
				: JSON.parse(JSON.stringify(this.selectedData[this.crmType] || []))
			this.list.forEach((rowItem) => {
				const crmIdKey = this.crmType + 'Id'
				const selectedIndex = selectedData.findIndex(
					(selectItem) => selectItem[crmIdKey] == rowItem[crmIdKey]
				)
				if (selectedIndex > -1) {
					selectedData.splice(selectedIndex, 1)
				}
			})
			selectedData = selectedData.concat(this.selectedItem)
			// debugger
			this.$emit('changeCheckout', {
				data: selectedData,
				type: this.crmType
			})
		},
		clearAll() {
			this.$refs.relativeTable.clearSelection()
		},
		// 清空已选
		clearSelected() {
			this.$emit('changeCheckout', {
				data: [],
				type: this.crmType
			})
			this.$refs.relativeTable.clearSelection()
		},
		// 	当用户手动勾选全选 Checkbox 时触发的事件
		selectAll() {},
		// 进行搜索操作
		searchInput() {
			this.currentPage = 1
			this.totalPage = 1
			this.getList()
		},
		changePage(type) {
			if (type == 'up') {
				this.currentPage = this.currentPage - 1
			} else if (type == 'down') {
				this.currentPage = this.currentPage + 1
			}
			if (this.currentPage <= this.totalPage && this.currentPage >= 1) {
				this.getList()
			}
		},
		createByNum() {
			const searchParams = this.$refs.search.getSubmitValue()
			this.changeCreateViewField(searchParams.entity.num)
		},
		changeCreateViewField(num) {
			this.$bus.emit('create_fields_change_field', {
				fieldName: 'contract_id',
				name: '保单号',
				formType: 'text',
				placeholder: '请输入保单号',
				isNull: 1,
				value: num
			})
		},
		// 底部信息
		getFootContent({ type, name, fieldName }) {
			if (type === 'total') {
				const value = this.selectedData[this.crmType]
					.map((row) => row[fieldName])
					.filter((val) => Number(val))
					.reduce((total, val) => total + val * 1, 0)
					.toFixed(2)
				return `${name}: ${value}`
			} else if (type === 'length') {
				const value = this.selectedData[this.crmType].length
				return `${name}: ${value}`
			}
		}
	}
}
</script>
<style lang="scss" scoped>
@import '@/styles/mixin.scss';
.cr-body-content {
	position: relative;
	background-color: white;
	border-bottom: 1px solid $xr-border-line-color;
	display: flex;
	flex-direction: column;
	height: 100%;
}

.content-header {
	position: relative;
	padding: 10px 20px;
	flex-wrap: nowrap;
	.search-container {
		flex: 1 1;
		margin: 0;
		padding-right: 10px;
	}
	.header-button {
		flex: 0;
		margin-top: 5px;
	}
}
.content-body {
	flex: 1;
	position: relative;
}
.cr-table {
	position: absolute;
	@include absCover;
	// flex: 1;
}

//表尾 上一页按钮
.table-footer {
	padding: 8px 135px 8px 8px;
	text-align: right;
	display: flex;
	align-items: center;
}

.el-table ::v-deep thead th {
	font-weight: 400;
	font-size: 12px;
}

.el-table ::v-deep tbody tr td {
	font-size: 12px;
}

.el-table.single ::v-deep thead .el-checkbox {
	display: none;
}
</style>
